import json
import random
import time
import os
import pandas as pd
import requests

session = requests.Session()


def random_wait():
    # 生成一个介于1到5秒之间的随机浮点数
    wait_time = random.uniform(1, 2)
    print(f"Waited for {wait_time:.2f} seconds")
    # 等待指定的秒数
    time.sleep(wait_time)


def download_image(url: str,
                   file_name: str = '',
                   file_path: str = './') -> None:
    '''
    图片下载器

    Args:
        url (str): 图片链接
        file_name (str): 文件名(需后缀)
        file_path (str): 保存目录
    '''
    if file_name == '':
        file_name = url.split('/')[-1]
    try:
        response = session.get(url)
        response.raise_for_status()
        with open(file_path + file_name, 'wb') as f:
            f.write(response.content)
        print(f'[Download Success] {file_name} ')
    except Exception as e:
        print(e)
    finally:
        random_wait()


def load_json_to_dict(file_path: str) -> dict:
    '''
    读取`json`并转化为`dict`
    :param {str} file_path
    :return {*}
    '''
    with open(file_path, 'r', encoding='utf-8') as f:
        return json.load(f)


def save_dict_to_json(data: dict, file_path: str) -> None:
    '''
    将`dict`转化为`json`并保存

    Args:
        data (dict): dict数据
        file_path (str): 保存目录
    '''

    with open(file_path, 'w', encoding='utf-8') as f:
        json.dump(data, f, ensure_ascii=False)
        print(f'Save {file_path} Success')

def load_xlxs_to_list(file_path: str,
                      columns_to_load: list,
                      sheet_name: str = 'Sheet1') -> list:
    '''
    读取`xlsx`，加载指定列，并转化为`list`
    
    Args:
    file_path (str): excle文件路径
    columns_to_load (list): 需要加载的列
    sheet_name (str): 加载的表名
    
    '''
    # 加载指定列
    data = pd.read_excel(file_path,
                         sheet_name=sheet_name,
                         usecols=columns_to_load)
    values_list = data[columns_to_load].values.flatten().tolist()
    return values_list
